package com.codedancer.campus.client.schedule;

import cn.hutool.core.util.ObjectUtil;
import com.codedancer.campus.common.enums.ViewNumberKeyEnum;
import com.codedancer.campus.common.utils.RedisUtil;
import com.codedancer.campus.mapper.LostFoundItemMapper;
import com.codedancer.campus.po.LostFoundItem;
import java.util.Set;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 失物招领定时任务
 */
@Component
@Slf4j
public class LostFoundItemSchedule {

    @Autowired
    private LostFoundItemMapper lostFoundItemMapper;
    @Autowired
    private RedisUtil redisUtil;
    // 注入浏览记录redisTemplate
    @Resource(name = "viewRedisTemplate")
    private StringRedisTemplate viewRedisTemplate;

    /**
     * 更新浏览记录 每天凌晨两点跑一次
     */
    @Scheduled(cron = "0 0 2 * * ?")
    private void updateViewNumber() {
        redisUtil.setRedisTemplate(viewRedisTemplate);
        log.info("开始更新浏览记录");
        long start = System.currentTimeMillis();
        // 获取失物招领有关的key
        Set<String> keys = redisUtil.getKeys(ViewNumberKeyEnum.LOST_FOUND_ITEM + "*");
        for (String key : keys) {
            Long viewNumber = redisUtil.size(key);
            String[] split = key.split(":");
            LostFoundItem lostFoundItem = lostFoundItemMapper.selectById(split[1]);
            if (ObjectUtil.isNotEmpty(lostFoundItem)){
                lostFoundItem.setViewNumber(lostFoundItem.getViewNumber() + viewNumber.intValue());
                lostFoundItemMapper.updateById(lostFoundItem);
            }
            // 删除key
            redisUtil.delete(key);
        }
        long end = System.currentTimeMillis();
        log.info("失物招领物品浏览量入库结束，耗时：{}", end - start);
    }

    /**
     * 每一小时执行一次检查redis中失物招领是否存在
     */
    @Scheduled(cron = "0 0 */1 * * ?")
    private void checkLostFoundItemExist() {
        redisUtil.setRedisTemplate(viewRedisTemplate);
        log.info("开始检查Redis中失物招领存在性问题");
        long start = System.currentTimeMillis();
        // 获取失物招领有关的key
        Set<String> keys = redisUtil.getKeys(ViewNumberKeyEnum.LOST_FOUND_ITEM + "*");
        for (String key : keys) {
            String[] split = key.split(":");
            String uuid = split[1];
            if (!lostFoundItemMapper.existsByUuId(uuid)) {
                log.info("删除不存在Key，{}", key);
                // 不存在，直接删除key
                redisUtil.delete(key);
            }
        }
        long end = System.currentTimeMillis();
        log.info("完成检查Redis中失物招领存在性问题，耗时：{}", end - start);
    }
}
